package com.admin4j.server.system.service.impl;

import com.admin4j.framework.mp.service.impl.BizServiceImpl;
import com.admin4j.server.system.entity.SysMenu;
import com.admin4j.server.system.entity.event.SysMenuCreateEvent;
import com.admin4j.server.system.entity.vo.MenuVO;
import com.admin4j.server.system.mapper.SysMenuMapper;
import com.admin4j.server.system.service.ISysMenuService;
import com.admin4j.spring.util.SpringUtils;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * <p>
 * 菜单权限表 服务实现类
 * </p>
 *
 * @author andanyang
 * @since 2023-11-14
 */
@Service
public class SysMenuServiceImpl extends BizServiceImpl<SysMenuMapper, SysMenu> implements ISysMenuService {

    @Override
    public List<SysMenu> menusByUserId(Long userId) {
        return list();
    }

    /**
     * 根据该用户目录树
     *
     * @param userId if null 查询全部
     * @return
     */
    @Override
    public List<MenuVO> treeByUserId(Long userId) {
        List<SysMenu> menus = menusByUserId(userId);

        return buildMenus(menus, 0L);
    }


    /**
     * 编译菜单树
     *
     * @param menus    菜单s
     * @param parentId 父节点id
     * @return
     */
    protected List<MenuVO> buildMenus(List<SysMenu> menus, Long parentId) {

        List<MenuVO> resultMenus = new ArrayList<>();
        for (SysMenu menu : menus) {

            if (Objects.equals(menu.getParentId(), parentId)) {

                MenuVO menuVO = new MenuVO(menu);

                resultMenus.add(menuVO);
                List<MenuVO> subMenus = buildMenus(menus, menu.getMenuId());
                menuVO.setChildren(subMenus);
            }
        }
        return resultMenus;
    }


    @Override
    protected void afterSave(SysMenu entity) {

        SpringUtils.getApplicationContext().publishEvent(new SysMenuCreateEvent(entity));
    }
}
